import argparse
import logging
import os
import signal
import sys
import threading
from utils.db_pool import MySQLConnectionPool
import queue
from DataService import DataService

# 初始化日志
logging.basicConfig(filename='error/info.log', level=logging.INFO, encoding='utf-8')

# 初始化数据库连接池
pool = MySQLConnectionPool()

def signal_handler(signal, frame):
    logging.info('接收到信号: %s', signal)
    logging.shutdown()
    sys.stdout.flush()
    sys.stderr.flush()
    os._exit(0)

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGSEGV, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

dataService = DataService()
dataService.get_apply_key()

def sync_api_data(thread_id, table_name, modelId, result_queue):
    try:
        conn = pool.get_connect()
        cursor = conn.cursor()
        servCode = "EXTLAB-AA25"
        limit = 5
        skip_rows = thread_id * limit
        sql_query = f"SELECT id, phone, month FROM {table_name} WHERE is_check=0 LIMIT {limit} OFFSET {skip_rows}"
        cursor.execute(sql_query)
        results = cursor.fetchall()

        if not results:
            result_queue.put(False)
            return

        for row in results:
            id, phone, mon = row
            mon = str(mon)
            requestXml = dataService.create_xml_phone(servCode, modelId, phone, mon)
            responseXml = dataService.do_post(requestXml)
            responseRs = dataService.parse_xml(responseXml)
            rsCode, billing, value, is_valid = responseRs

            if rsCode != "0":
                errorLogDir = "/data/dev10086/result/"
                with open(f"{errorLogDir}{modelId}_error.log", "a", encoding='utf-8') as f:
                    f.write(f"{id}|{phone}|{mon}|{rsCode}\n")
                update_sql = f"UPDATE {table_name} SET is_check=1 WHERE id={id}"
            else:
                update_sql = f"UPDATE {table_name} SET is_billing={billing}, value={value}, is_valid={is_valid}, is_check=1 WHERE id={id}"
            
            cursor.execute(update_sql)
            conn.commit()

        result_queue.put(True)
    except Exception as e:
        logging.exception('Thread %s encountered an error: %s', thread_id, e)
        result_queue.put(False)
    finally:
        cursor.close()
        conn.close()

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--type", help="the model type's sign, such as 'zaixin_model_hq' or 'zaixin_model_zx' or 'zaixin_model_zf'")
    args = parser.parse_args()

    type = args.type
    if type is None:
        print("Please input the type.")
        return

    modelId = f"zaixin_model_{type}"
    # type => table
    # hq => data_hunqing
    # zx => data_zhuangxiu
    # zf => data_zhifu
    # jy => data_jiaoyu
    # fl => data_falv
    # 非这几种抛出提示
    type_to_table = {
        "hq": "data_hunqing",
        "zx": "data_zhuangxiu",
        "zf": "data_zhifu",
        "jy": "data_jiaoyu",
        "fl": "data_falv"
    }

    if type not in type_to_table:
        print(f"Unsupported type: {type}. Please use one of the following: {', '.join(type_to_table.keys())}")
        return

    table_name = type_to_table[type]
    
    while True:
        threads = []
        result_queue = queue.Queue()
        for i in range(10):
            t = threading.Thread(target=sync_api_data, args=(i, table_name, modelId, result_queue))
            threads.append(t)
            t.start()

        for t in threads:
            t.join()

        results = [result_queue.get() for _ in range(len(threads))]
        if all(result == False for result in results):
            print("所有线程的结果都是False，结束进程。")
            break

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        logging.exception('程序异常退出: %s', e)
        raise